package cn.hg.solon.youcan.easyquery.interceptor;

import java.util.function.Supplier;

import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.reflect.ClassUtil;
import org.dromara.hutool.core.reflect.FieldUtil;
import org.dromara.hutool.core.util.ObjUtil;
import org.noear.solon.Solon;

import com.easy.query.core.basic.extension.interceptor.EntityInterceptor;
import com.easy.query.core.expression.sql.builder.EntityInsertExpressionBuilder;
import com.easy.query.core.expression.sql.builder.EntityUpdateExpressionBuilder;

import cn.hg.solon.youcan.common.constant.WebConstants;

/**
 * 对象拦截器
 * 
 * @author 胡高
 */
public class EqEntityInterceptor implements EntityInterceptor {

    /* (non-Javadoc)
     * @see com.easy.query.core.basic.extension.interceptor.Interceptor#apply(java.lang.Class)
     */
    @Override
    public boolean apply(Class<?> entityClass) {
        return true;
    }

    /* (non-Javadoc)
     * @see com.easy.query.core.basic.extension.interceptor.EntityInterceptor#configureInsert(java.lang.Class, com.easy.query.core.expression.sql.builder.EntityInsertExpressionBuilder, java.lang.Object)
     */
    @Override
    public void configureInsert(Class<?> entityClass, EntityInsertExpressionBuilder entityInsertExpressionBuilder,
        Object entity) {
        Supplier<Integer> getter = Solon.context().getBean(WebConstants.USER_ID_GETTER);
        if (ObjUtil.isNull(getter)) {
            return;
        }
        try {
            /*
             * 配置自动插入时的值
             */
            BeanUtil.setFieldValue(entity, "creator", getter.get());
            BeanUtil.setFieldValue(entity, "createdDatetime", DateUtil.now());
        } catch (Exception e) {
        }
    }

    /* (non-Javadoc)
     * @see com.easy.query.core.basic.extension.interceptor.EntityInterceptor#configureUpdate(java.lang.Class, com.easy.query.core.expression.sql.builder.EntityUpdateExpressionBuilder, java.lang.Object)
     */
    @Override
    public void configureUpdate(Class<?> entityClass, EntityUpdateExpressionBuilder entityUpdateExpressionBuilder,
        Object entity) {
        Supplier<Integer> getter = Solon.context().getBean(WebConstants.USER_ID_GETTER);
        if (ObjUtil.isNull(getter)) {
            return;
        }
        try {
            /*
             * 配置更新是需要修改的值
             */
            BeanUtil.setFieldValue(entity, "editor", getter.get());
            BeanUtil.setFieldValue(entity, "editedDatetime", DateUtil.now());
        } catch (Exception e) {
        }
    }

    /* (non-Javadoc)
     * @see com.easy.query.core.basic.extension.interceptor.Interceptor#name()
     */
    @Override
    public String name() {
        return ClassUtil.getClassName(EqEntityInterceptor.class, true);
    }

}
